<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          v-if="selectionStatus === 0"
          type="primary"
          plain
          size="mini"
          @click="handleTemporary('start')"
          >开始预选</el-button
        >
        <el-button
          v-preventReClick
          v-if="selectionStatus === 1"
          style="margin-right: 10px"
          type="primary"
          plain
          size="mini"
          @click="handleTemporary('cancel')"
          >取消预选</el-button
        >
        <el-button
          v-preventReClick
          v-if="selectionStatus === 2"
          type="primary"
          plain
          size="mini"
          @click="handleTemporary('finish')"
          >完成预选</el-button
        >
        <el-button
          v-if="selectionStatus === 3"
          v-preventReClick
          type="primary"
          plain
          size="mini"
          @click="curriculaVariableOpen = true"
          >开始正选</el-button
        >
        <el-button
          v-preventReClick
          v-if="selectionStatus === 4"
          type="primary"
          plain
          size="mini"
          @click="handleSelection('cancel')"
          >取消正选</el-button
        >
        <el-button
          v-preventReClick
          v-if="selectionStatus === 5"
          type="primary"
          plain
          size="mini"
          @click="handleSelection('finish')"
          >完成正选</el-button
        >
      </el-col>
      <!-- <div
        style="height: 32px; line-height: 32px; color: red; font-size: 12px"
        v-if="selectionStatus === 1 || selectionStatus === 4"
      >
        {{ timeshow }}
      </div>
      <div
        style="height: 32px; line-height: 32px"
        v-if="selectionStatus === 0 || selectionStatus === 3"
      >
        <el-checkbox
          v-if="preStatus !== 2"
          style="margin-left: 20px"
          v-model="isSkipTemporary"
          >跳过预选</el-checkbox
        >
        <el-checkbox v-model="isSetTime">设置时间</el-checkbox>
        <el-date-picker
          v-if="isSetTime"
          style="margin-left: 20px"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="TemporaryTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div> -->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        :label="`${$courseName ? $courseName : '课程'}`"
        prop="courseId"
      >
        <el-select
          filterable
          v-model="queryParams.courseId"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(item, index) in course"
            :key="index"
            :label="item.courseName"
            :value="item.courseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="`${$workstationName ? $workstationName : '工作站'}`"
        prop="workstationId"
      >
        <el-select
          filterable
          v-model="queryParams.workstationId"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(item, index) in workstation"
            :key="index"
            :label="item.workstationName"
            :value="item.workstationId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        :label="`${$courseName ? $courseName : '课程'}编号`"
        align="center"
        prop="postId"
      />
      <el-table-column
        :label="`${$courseName ? $courseName : '课程'}名称`"
        align="center"
        prop="postCode"
      />
      <el-table-column
        :label="`${$workstationName ? $workstationName : '工作站'}`"
        align="center"
        prop="postName"
      />

      <el-table-column label="类型" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column :label="`${$hourAmount?$hourAmount:'课时量'}(周)`" align="center" prop="postSort" />
      <el-table-column label="地址" align="center" prop="postSort" />
      <el-table-column
        sortable=""
        label="已选人数"
        align="center"
        prop="postSort"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            @click="handleLimit(scope.row)"
            >人数限制</el-button
          >
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            >预选详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 人数限制 -->
    <workStationPeopleLimit
      :open.sync="limitOpen"
      @refresh="getList"
      :id="handleId"
    ></workStationPeopleLimit>
    <!-- 预选详情 -->
    <temporaryDetail
      :open.sync="temporaryDetailOpen"
      @refresh="getList"
      :id="handleId"
    ></temporaryDetail>
    <!-- 开始正选选择时间 -->
    <el-dialog
      title="开始正选"
      :visible.sync="curriculaVariableOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
      append-to-body
      @close="cancel()"
    >
      <el-form   @submit.native.prevent  ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选课时间" prop="TemporaryTime">
          <el-date-picker
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.TemporaryTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="curriculaVariableOpen=false">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  updatePost_cancelSelection,
  updatePost_selection,
  listPost_temporary,
  addPost_temporary,
  listPost_selection,
  addPost_selection,
  temporarylastOne,
  selectionlastOne,
  delPost_selection,
} from "@/api/course/curriculaVariable";
import { listPost_course } from "@/api/course/course";
import { listPost_workstation } from "@/api/workstation/workstation";

import workStationPeopleLimit from "@/components/workStationPeopleLimit";
import temporaryDetail from "@/components/temporaryDetail";
export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  components: { workStationPeopleLimit, temporaryDetail },
  data() {
    return {
      curriculaVariableOpen:false,
      form: {
        TemporaryTime: undefined,
      },
      // 表单校验
      rules: {
        TemporaryTime: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
      },
      handleId: 0,
      // 预选详情组件
      temporaryDetailOpen: false,
      // 人数限制组件
      limitOpen: false,
      //
      id: "",
      preStatus: "", //用于处理跳过预选这个按钮的显示
      clock: "",
      /* 倒计时 */
      timeshow: "",
      isSetTime: false,
      isSkipTemporary: false,
      TemporaryTime: "",
      // 0未开始预选 1倒计时预选 2预选中 3结束预选开始正选 4正选倒计时中 5正选结束（0）
      selectionStatus: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workstationId: undefined,
        courseId: undefined,
      },
      workstation: [],
      course: [],
    };
  },
  created() {
    this.getList();
    this.getWorkstation();
    this.getCourse();
    this.getStatus();
  },
  watch: {
    isSkipTemporary(e) {
      this.selectionStatus = e ? 3 : 0;
    },
  },
  destroyed() {
    clearInterval(this.clock);
  },
  methods: {
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.handleSelection("start");
        }
      });
    },
    /* 人数限制 */
    handleLimit(row) {
      this.limitOpen = true;
      this.handleId = row.xxxx;
    },
    /* 预选详情 */
    handleDetail(row) {
      this.temporaryDetailOpen = true;
      this.handleId = row.xxxx;
    },
    /* 倒计时 */
    size(number) {
      return number < 10 ? "0" + number : number;
    },
    djs(data) {
      var preDate = new Date(data);
      var preTimes = preDate.getTime(); // 获取目标日期距离1970年1月1日毫秒数
      this.clock = setInterval(() => {
        let nowDate = new Date();
        let nowTimes = nowDate.getTime();
        let lastTimes = preTimes - nowTimes;
        let lastSeconds = parseInt(lastTimes / 1000);
        // 倒计时结束
        if (lastSeconds == 0) {
          console.log("倒计时结束");
          clearInterval(this.clock);
          if (this.selectionStatus == 1) {
            this.selectionStatus = 2;
            // this.getStatus();
          }
          if (this.selectionStatus == 4) {
            this.selectionStatus = 5;
            // this.getStatus();
          }
          return false;
        }
        let lastD = this.size(parseInt(lastSeconds / 3600 / 24));
        let lastH = this.size(parseInt((lastSeconds / 3600) % 24));
        let lastM = this.size(parseInt((lastSeconds / 60) % 60));
        let lastS = this.size(parseInt(lastSeconds % 60));
        // 7. 将结果放入div
        this.timeshow =
          lastD + "天" + lastH + "小时" + lastM + "分钟" + lastS + "秒";
      }, 1000);
    },
    /* 获取预选 正选状态 */
    /* 0未开始预选 1倒计时预选 2预选中 3结束预选开始正选 4正选倒计时中 5正选中（0） */
    getStatus() {
      selectionlastOne().then((res) => {
        if (res.data && res.data.realStatus !== 2) {
          this.preStatus = res.data.preStatus;
          this.id = res.data.id;
          // 预选 正选状态中
          // 开始预选
          if (res.data.preStatus == 0) {
            // 倒计时中
            if (res.data.beginDatePre) {
              this.selectionStatus = 1;
              this.djs(res.data.beginDatePre);
            }
            // 没有倒计时
            else {
              this.selectionStatus = 0;
            }
          }
          // 预选中
          if (res.data.preStatus == 1) {
            this.selectionStatus = 2;
          }
          // 预选结束 开始正选
          if (res.data.preStatus == 2) {
            if (res.data.realStatus == 0) {
              // 倒计时中
              if (res.data.beginDate) {
                this.selectionStatus = 4;
                this.djs(res.data.beginDate);
              }
              // 没有倒计时
              else {
                this.selectionStatus = 3;
              }
            }
            // 正选中
            if (res.data.realStatus == 1) {
              this.selectionStatus = 5;
            }
            // 正选结束
            if (res.data.realStatus == 2) {
              this.selectionStatus = 0;
            }
          }
        }
        // 获取最新接口没有值 则代表没有在 预选正选中
        else {
          this.selectionStatus = 3;
        }
      });
    },
    /* 开始预选 */
    handleTemporary(type) {
      console.log(type);
      // 开始预选
      if (type == "start") {
        if (this.isSetTime && this.TemporaryTime == "") {
          this.$modal.msgError("请设置时间");
          return false;
        }
        if (new Date(this.TemporaryTime[0]) < new Date()) {
          this.$modal.msgError("开始时间早于当前时间，请重新设置");
          return false;
        }
        this.$modal
          .confirm("确定开始预选")
          .then(() => {
            addPost_selection({
              beginDatePre: this.isSetTime ? this.TemporaryTime[0] : "",
              endDatePre: this.isSetTime ? this.TemporaryTime[1] : "",
              preStatus: this.isSetTime ? 0 : 1,
              realStatus: 0,
              schoolId: this.$store.getters.schoolId,
              temporaryStatus: 0,
            }).then((res) => {
              this.$modal.msgSuccess("预选成功");
              this.getStatus();
            });
          })
          .catch(() => {});
      }
      // 结束预选
      else if (type == "finish") {
        this.$modal
          .confirm("确定结束预选")
          .then(() => {
            updatePost_selection({
              id: this.id,
              preStatus: 2,
              realStatus: 0,
              schoolId: this.$store.getters.schoolId,
            }).then((res) => {
              this.$modal.msgSuccess("结束预选成功");
              this.getStatus();
            });
          })
          .catch(() => {});
      }
      // 取消删除预选
      else {
        this.$modal
          .confirm("确定取消预选")
          .then(() => {
            delPost_selection(this.id).then((res) => {
              this.$modal.msgSuccess("取消预选成功");
              clearInterval(this.clock);
              this.selectionStatus = 0;
            });
          })
          .catch(() => {});
      }
    },
    /* 正选操作 */
    handleSelection(type) {
      // 开始正选
      if (type == "start") {
        if (this.isSetTime && this.TemporaryTime == "") {
          this.$modal.msgError("请设置时间");
          return false;
        }
        if (new Date(this.TemporaryTime[0]) < new Date()) {
          this.$modal.msgError("开始时间早于当前时间，请重新设置");
          return false;
        }
        this.$modal
          .confirm("确定开始正选")
          .then(() => {
            // // 正常通过预选触发
            // if (!this.isSkipTemporary) {
            //   updatePost_selection({
            //     id: this.id,
            //     beginDate: this.isSetTime ? this.TemporaryTime[0] : "",
            //     endDate: this.isSetTime ? this.TemporaryTime[1] : "",
            //     preStatus: 2,
            //     realStatus: this.isSetTime ? 0 : 1,
            //     schoolId: this.$store.getters.schoolId,
            //   }).then((res) => {
            //     this.$modal.msgSuccess("正选成功");
            //     this.getStatus();
            //   });
            // }
            // // 跳过预选触发
            // else {
            addPost_selection({
              beginDate:  this.form.TemporaryTime[0] ,
              endDate:  this.form.TemporaryTime[1] ,
              preStatus: 2,
              realStatus: this.isSetTime ? 0 : 1,
              schoolId: this.$store.getters.schoolId,
              temporaryStatus: 1,
            }).then((res) => {
              this.$modal.msgSuccess("正选成功");
              this.getStatus();
              this.curriculaVariableOpen=false
            });
            // }
          })
          .catch(() => {});
      }
      // 结束正选
      else if (type == "finish") {
        this.$modal
          .confirm("确定结束正选")
          .then(() => {
            updatePost_selection({
              id: this.id,
              preStatus: 2,
              realStatus: 2,
              schoolId: this.$store.getters.schoolId,
            }).then((res) => {
              this.$modal.msgSuccess("结束正选成功");
              this.getStatus();
              this.isSkipTemporary = false;
            });
          })
          .catch(() => {});
      }
      // 取消删除正选
      else {
        this.$modal
          .confirm("确定取消正选")
          .then(() => {
            updatePost_cancelSelection({
              beginDate: "",
              endDate: "",
              id: this.id,
              preStatus: 2,
              realStatus: 0,
              schoolId: this.$store.getters.schoolId,
            }).then((res) => {
              this.$modal.msgSuccess("取消正选成功");
              clearInterval(this.clock);
              this.selectionStatus = 3;
            });
          })
          .catch(() => {});
      }
    },
    /* 获取工作站 课程接口 */
    getWorkstation() {
      listPost_workstation({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((res) => {
        this.workstation = res.rows;
      });
    },
    getCourse() {
      listPost_course({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
      }).then((res) => {
        this.course = res.rows;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPost_temporary(this.queryParams).then((response) => {
        //XXX :这里定义了假数据
        this.postList = [1];
        //this.postList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
